/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-10-10
 * Time: 19:21
 */
public class Sort {
    public static void selectSort(int[] array){
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            for (int j = i+1; j < array.length; j++) {
                if(array[i] > array[j]){
                    minIndex = j;
                }
            }
            swap(array, minIndex, i);
        }
    }

    private static void swap(int[] array, int minIndex, int i) {
        int tmp = array[minIndex];
        array[minIndex] = array[i];
        array[i] = tmp;
    }

    public static void heapSort(int[] array){
        createheap(array);
        int end = array.length-1;
        while(end > 0){
            swap(array, 0, end);
            siftDown(array, 0, end);
            end--;
        }
    }

    private static void createheap(int[] array) {
        for (int parent = (array.length-2) / 2; parent >= 0; parent--) {
            siftDown(array, 0, array.length);
        }
    }

    private static void siftDown(int[] array, int parent, int length) {
        int child = 2*parent+1;
        while(child < length){
            if(child+1 < length && array[child] < array[child+1]){
                child++;
            }
            if(array[child] > array[parent]){
                swap(array, child, parent);
                parent = child;
                child = 2*parent+1;
            }else{
                break;
            }
        }

    }

    public static void bubbuleSort(int[] array){
        for (int i = 0; i < array.length-1; i++) {
            boolean flg = false;
            for (int j = 0; j < array.length-1 - i; j++) {
                if(array[j] > array[j+1]){
                    swap(array, j+1, j);
                    flg = true;
                }

            }
            if(!flg){
                break;
            }
        }
    }

    public static void quickSort(int[] array){
        quick(array, 0, array.length-1);
    }

    private static void quick(int[] array, int start, int end) {
        if(start >= end){
            return;
        }
        int pivot = partition(array, start, end);
        quick(array, start, pivot-1);
        quick(array, pivot+1, end);
    }

    private static int partition(int[] array, int left, int right) {
        int tmp = array[left];

        while(left < right){
            while(left < right && array[right] >= tmp){
                right--;
            }
            array[left] = array[right];

            while(left < right && array[left] <= tmp){
                left++;
            }
            array[right] = array[left];

        }
        array[left] = tmp;
        return left;
    }
}
